﻿package com.ccx.coachsite.util.net;



import java.io.BufferedReader;
import java.io.File;
import java.io.FileReader;
import java.io.FileWriter;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.io.Writer;
import java.util.zip.GZIPInputStream;

import org.apache.http.Header;
import org.apache.http.HttpResponse;
import org.apache.http.client.ClientProtocolException;
import org.apache.http.client.methods.HttpGet;
import org.apache.http.impl.client.DefaultHttpClient;
import org.apache.http.params.BasicHttpParams;
import org.apache.http.params.HttpConnectionParams;
import org.apache.http.params.HttpParams;
import org.apache.http.params.HttpProtocolParams;
import org.apache.http.util.EntityUtils;
import org.json.JSONException;
import org.json.JSONObject;

import com.ccx.coachsite.data.ResultCode;
import com.ccx.coachsite.data.SystemConst;
import com.ccx.coachsite.util.FileUtil;
import com.ccx.coachsite.util.LogUtil;

public class JSONUtil {
	static String tag = "JSONUtil";
	//连接超时
	static final int HTTPCON_TIMEOUT = 30000;
	//读取数据超时
	static final int SOCKET_TIMEOUT = 30000;

	public static String get(String url) throws ClientProtocolException, IOException,
			JSONException {
		HttpGet request = new HttpGet(url);
		HttpProtocolParams.setUserAgent(request.getParams(),
				SystemConst.PACKAGE_NAME);
		request.addHeader("Accept-Encoding", "gzip");
		// 设置超时
		HttpParams params = new BasicHttpParams();
		HttpConnectionParams.setConnectionTimeout(params, HTTPCON_TIMEOUT);
		HttpConnectionParams.setSoTimeout(params, SOCKET_TIMEOUT);

		// 发送请求
		HttpResponse httpResponse = new DefaultHttpClient(params)
				.execute(request);
		Header contentEncoding = httpResponse
				.getFirstHeader("Content-Encoding");
		String retSrc = null;
		if (contentEncoding != null
				&& contentEncoding.getValue().equalsIgnoreCase("gzip")) {
			InputStream inputStream = httpResponse.getEntity().getContent();
			GZIPInputStream zipInputStream = new GZIPInputStream(inputStream);
			InputStreamReader reader = new InputStreamReader(zipInputStream);
			BufferedReader in = new BufferedReader(reader);
			StringBuffer sb = new StringBuffer();
			String line;
			while ((line = in.readLine()) != null) {
				sb.append(line);
			}
			in.close();
			reader.close();
			zipInputStream.close();
			inputStream.close();
			retSrc = sb.toString();
			LogUtil.d(tag, "返回的数据是gzip压缩");
		} else {
			retSrc = EntityUtils.toString(httpResponse.getEntity());
		}
		LogUtil.d(tag, url);
		LogUtil.d(tag, retSrc);
		return retSrc;
	}
	public static JSONObject requestJSON(String url)
			throws ClientProtocolException, IOException, JSONException {
		// 生成 JSON 对象
		JSONObject result = new JSONObject(get(url));
		return result;
	}
	
	public static JSONObject loadJSON(String url) {
		UrlParse parse = new UrlParse(url);
		UrlManager.setCommonUrlParam(parse);
		return loadJSON(parse.toString(),null);
	}
	public static JSONObject loadJSON(String url, String filePath) {
		JSONObject json = null;
		try {
			// 网络请求
			json = JSONUtil.requestJSON(url);
			// 本地保存
			JSONUtil.jsonObjectToFile(json, filePath);
			
			int code = json.getInt("Code");
			if (code != ResultCode.SUCESS) {
				LogUtil.e(tag,"result code 不为 0："+json);
			}
			
		} catch (Exception e) {
			e.printStackTrace();
			LogUtil.e(tag,
					"请求 json 数据异常,url:" + url);
		}
		return json;
	}

	public static void jsonObjectToFile(JSONObject object, String filePath)
			throws IOException {
		if (filePath == null)
			return;
		File f = FileUtil.createFile(filePath);
		if (!f.exists()) {
			f.createNewFile();
		}
		Writer writer = new FileWriter(filePath);
		writer.write(object.toString());
		writer.close();
	}

	// 异常在此处理，不抛出
	public static JSONObject fileToJsonObject(String filePath) {

		JSONObject o = null;
		if (filePath == null)
			return null;
		File f = new File(filePath);
		if (!f.exists()) {
			return null;
		}
		try {
			BufferedReader in = new BufferedReader(new FileReader(f));
			String str = "";
			String tmp;
			while ((tmp = in.readLine()) != null) {
				str += tmp;
			}
			in.close();
			o = new JSONObject(str);
		} catch (Exception e) {
			e.getStackTrace();
			LogUtil.w(tag, "加载json文件失败" + e.getMessage());
		}
		return o;
	}
	
	public static String getCommonUrlParam(int act) {
		String urlParam = "act="+act+"&";
		UrlParse parse = new UrlParse();
		UrlManager.setCommonUrlParam(parse);
		return urlParam += parse.getUrlParam();
	}
}
